package com.caigou.controller;

import com.alibaba.fastjson.JSONObject;
import com.caigou.component.RedisStringComponent;
import com.caigou.component.RequestComponent;
import com.caigou.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class TestController {

    @Resource
    private RedisStringComponent redisStringComponent;

    @RequestMapping("/TestRequest")
    public Result TestRequest(){
        // 请求token
        String token = redisStringComponent.get("wx_access_token");
        if (null == token || ("").equals(token)){
            log.info("没有从缓存中获取到token的值改为直接请求微信获取");
            String tokenResponse = RequestComponent.HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx20c094354adc43d6&secret=14ce3bf116a1866e905d61ece6306bca");
            if (null != tokenResponse){
                JSONObject tokenJSON = JSONObject.parseObject(tokenResponse);
                token = tokenJSON.getString("access_token");
                redisStringComponent.setEx("wx_access_token", token, 7000, TimeUnit.SECONDS);
            }
        }
        Map<String, String> map = new HashMap<>();
        // 请求ticket
        String ticketResponse = RequestComponent.HttpGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+token+"&type=jsapi");
        if (null != ticketResponse){
            JSONObject ticketJSON = JSONObject.parseObject(ticketResponse);
            String ticket = ticketJSON.getString("ticket");
            map.put("ticket",ticket);
            String noncestr = String.valueOf((System.currentTimeMillis() / 1000));
            map.put("noncestr",noncestr);
            String timestamp = String.valueOf((System.currentTimeMillis() / 1000));
            map.put("timestamp", timestamp);
            String url = "https://testapi.caigou2003.com/yin_stest.html";
            map.put("url",url);
            String signStr = "jsapi_ticket="+ticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url;
            String sign = DigestUtils.shaHex(signStr);
            log.info("sign={}",sign);
            map.put("sign",sign);
        }
        return Result.success(map);
    }
}
